/*
 * @Author: your name
 * @Date: 2021-04-05 15:40:53
 * @LastEditTime: 2021-05-11 17:05:20
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \chronic-back-end\module\consultMod\service.go
 */
package consultMod

import (
	"chronic/common"
	"chronic/module/userMod"
)

func addOneConsultation(patientId uint, doctorId uint, content string) (*Consultation, error) {
	db := common.UseDb()
	con := Consultation{PatientID: patientId, DoctorID: doctorId, Content: content}
	err := db.Save(&con).Error
	return &con, err
}

func findConsultationsByPatientId(patientId uint) ([]*Consultation, error) {
	db := common.UseDb()
	var cons []*Consultation
	err := db.Where("patient_id = ?", patientId).Preload("Doctor").Order("updated_at desc").Find(&cons).Error
	return cons, err
}

func findAllConsultations() ([]*Consultation, error) {
	db := common.UseDb()
	var cons []*Consultation
	err := db.Preload("Doctor").Preload("Patient").Order("created_at desc").Find(&cons).Error
	return cons, err
}

func findConsultsByUserId(userId uint) ([]*Consultation, error) {
	db := common.UseDb()
	var cons []*Consultation
	err := db.Where("patient_id=?", userId).Or("doctor_id=?", userId).Preload("Doctor").Preload("Patient").Find(&cons).Error
	return cons, err
}

func findConsultsByOther(condition string) ([]*Consultation, error) {
	db := common.UseDb()
	// 1,look for user in userMod.User{},and pick out the user's id
	// 2,look for cons in Consultation{} by the user's id picked out just now
	var user userMod.User
	db.Where("name=?", condition).Or("phone=?", condition).First(&user)
	cons, err := findConsultsByUserId(user.ID)
	// var cons []*Consultation
	// err := db.Where("doctor_id=?", user.ID).Or("patient_id=?", user.ID).Preload("Doctor").Preload("Patient").Find(&cons).Error
	return cons, err
}

func adminDeleteConsult(id uint) error {
	db := common.UseDb()
	err := db.Where("id = ?", id).Delete(&Consultation{}).Error
	return err
}
